class Solution {
public:
    unordered_map<char,unordered_set<char>>edge;
    unordered_map<char,int>in;
    string alienOrder(vector<string>& words) {
        for(auto &str:words)
        {
            for(auto x:str)
            {
                in[x]=0;
            }
        }
        int n=words.size();
        for(int i=0;i<n;i++)
        for(int j=i+1;j<n;j++)
        {
            bool tmp=add(words[i],words[j]);
            if(tmp==true)return "";
        }

        queue<char>q;
        for(auto [a,b]:in)
        {
            if(b==0)q.push(a);
        }
        string ret;
        while(q.size())
        {
            auto t=q.front();
            q.pop();
            ret+=t;
            for(auto x:edge[t])
            {
                if(--in[x]==0)q.push(x);
            }
        }

        for(auto [a,b]:in)
        if(b)return "";
        return ret;
    }


    bool add(string & s1,string&s2)
    {
        int n=min(s1.size(),s2.size());
        int i=0;
        for(;i<n;i++)
        {
            if(s1[i]!=s2[i])
            {
                char a=s1[i];
                char b=s2[i];
                if(!edge.count(a)||!edge[a].count(b))
                {
                    edge[a].insert(b);
                    in[b]++;
                }
                break;
            }
        }
        if(i==s2.size()&&i<s1.size())return true; 
        return false;
    }
};
